<template>
  <div class="crime-heatmap">
    <div class="chart-header">
      <h3>犯罪高发时间热力图</h3>
      <div class="time-range">近一年数据统计</div>
    </div>
    <div class="heatmap-container" ref="heatmapContainer"></div>
  </div>
</template>

<script>
import { Chart } from '@antv/g2'

export default {
  name: 'CrimeHeatmap',
  data() {
    return {
      chart: null,
      mockData: []
    }
  },
  mounted() {
    this.generateMockData()
    this.initChart()
    // this.startDataUpdate()
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.destroy()
    }
    if (this.updateTimer) {
      clearInterval(this.updateTimer)
    }
  },
  methods: {
    generateMockData() {
      // 重新定义模拟数据：1-12月，每小时间隔
      this.mockData = []

      // 为每个月份的每小时生成数据
      for (let month = 1; month <= 12; month++) {
        const monthName = `${month}月`

        // 基础犯罪率，根据月份调整（冬季和夏季可能更高）
        const baseRate = month <= 2 || month >= 11 ? 1.2 : // 冬季
                         month >= 6 && month <= 8 ? 1.1 : // 夏季
                         1.0 // 其他季节

        for (let hour = 0; hour < 24; hour++) {
          // 根据时间段调整犯罪率
          let hourMultiplier = 1.0
          if (hour >= 22 || hour <= 4) {
            // 深夜（22:00-04:00）
            hourMultiplier = 2.5
          } else if (hour >= 18 && hour <= 21) {
            // 傍晚（18:00-21:00）
            hourMultiplier = 1.8
          } else if (hour >= 12 && hour <= 17) {
            // 下午（12:00-17:00）
            hourMultiplier = 1.2
          } else if (hour >= 6 && hour <= 11) {
            // 上午（06:00-11:00）
            hourMultiplier = 0.8
          } else {
            // 凌晨（04:00-06:00）
            hourMultiplier = 0.6
          }

          // 计算最终值，添加随机波动
          const baseValue = Math.floor(baseRate * hourMultiplier * 10)
          const randomVariation = Math.floor((Math.random() - 0.5) * 6) // -3 到 +3 的随机值
          const value = Math.max(0, baseValue + randomVariation)

          this.mockData.push({
            x: hour,
            y: monthName,
            value: value
          })
        }
      }
    },

    initChart() {
      this.$nextTick(() => {
        if (this.chart) {
          this.chart.destroy()
        }

        const container = this.$refs.heatmapContainer
        if (!container) return

        this.chart = new Chart({
          container,
          autoFit: true,
          height: container.offsetHeight,
          options: {
            slider: false // 直接禁用缩略轴
          }
        })
        this.chart.data(this.mockData)

        this.chart.axis('y',{
          labelFill: '#fff',
        })

        this.chart.axis('x',{
          labelFill: '#fff',
        })

        this.chart
          .cell()
          .encode('x', 'x')
          .encode('y', 'y')
          .encode('color', 'value')
          .style('opacity', 0)
          .tooltip(false)
          .style({
            stroke: 'rgba(255,255,255,0.1)',
            lineWidth: 1
          })
          .tooltip({
            title: (d, y, value) => `${d.y} ${d.x}:00`,
            items: [
            (d, i, data, column) => ({
                name: '犯罪频次',
                value: d.value,
              })
            ]
          })
          // .tooltip('x*y*value', (x, y, value) => ({
          //   title: `${y} ${x}:00`,
          //   value: `犯罪频次: ${value}`
          // }))
          .slider(false)
          .animate('enter', { type: 'fadeIn', duration: 800 })

        this.chart.theme({
          background: 'transparent',
          view: {
            viewFill: 'transparent'
          }
        })

        this.chart.render()
        console.log(this.chart)
      })
    },

    startDataUpdate() {
      this.updateTimer = setInterval(() => {
        this.updateHeatmapData()
      }, 10000) // 每10秒更新一次
    },

    updateHeatmapData() {
      // 重新生成数据以模拟实时变化
      this.generateMockData()

      if (this.chart) {
        this.chart.changeData(this.mockData)
      }
    }
  }
}
</script>

<style scoped>
.crime-heatmap {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: linear-gradient(145deg,
      rgba(0, 80, 120, 0.12) 0%,
      rgba(0, 100, 140, 0.08) 30%,
      rgba(0, 60, 100, 0.05) 70%,
      rgba(0, 90, 130, 0.08) 100%),
    radial-gradient(circle at 30% 30%, rgba(255, 255, 255, 0.08) 0%, transparent 50%),
    rgba(0, 0, 0, 0.5);
  border-radius: 12px;
  padding: 10px;
  border: 1px solid rgba(0, 100, 150, 0.3);
  backdrop-filter: blur(10px);
  box-shadow:
    0 8px 32px rgba(0, 100, 150, 0.2),
    inset 0 1px 0 rgba(255, 255, 255, 0.1);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  /* margin-bottom: 15px; */
  flex-shrink: 0;
}

.chart-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  background: linear-gradient(45deg,
      rgba(0, 120, 160, 0.9) 0%,
      rgba(0, 100, 140, 0.8) 50%,
      rgba(0, 80, 120, 0.7) 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  text-shadow: 0 0 10px rgba(0, 100, 150, 0.4);
}

.time-range {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
  background: rgba(0, 100, 150, 0.2);
  padding: 4px 8px;
  border-radius: 4px;
  border: 1px solid rgba(0, 100, 150, 0.3);
}

.heatmap-container {
  flex: 1;
  /* min-height: 250px; */
  border-radius: 8px;
  overflow: hidden;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .crime-heatmap {
    padding: 15px;
  }

  .chart-header {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }

  .chart-header h3 {
    font-size: 14px;
  }

  .heatmap-container {
    min-height: 200px;
  }
}
</style>
